package com.neusoft.elmboot.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {

    /**
     * 拦截器核心方法，用于过滤请求和响应，进行用户认证处理
     * 
     * @param request  ServletRequest：HTTP 请求对象
     * @param response ServletResponse：HTTP 响应对象
     * @param chain    FilterChain：用于将请求传递给下一个过滤器或资源
     * @throws IOException      可能抛出的 IO 异常
     * @throws ServletException 可能抛出的 Servlet 异常
     */
    @Override
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String method = httpRequest.getMethod();
        
        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(method)) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 从 token 或 session 中获取用户信息，继续原有认证逻辑
        Object user = httpRequest.getSession().getAttribute("user");
        if (user == null) {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write("认证失败，无法访问系统资源");
            return;
        }

        // 继续处理其他请求
        chain.doFilter(request, response);
    }
}
